from typing import Optional
import typing

import PySide6.QtWidgets
from PySide6.QtCore import Qt
from PySide6.QtGui import QAction, QIcon
import PySide6.QtGui
from PySide6.QtWidgets import QHeaderView, QTreeWidget, QTreeWidgetItem
from .TreeWidgetItemABC import TreeWidgetItemABC

from ...HeaderView.HorizontalTreeHeaderView import HorizontalHeaderView


class TreeWidgetTrace(QTreeWidget):
    '''
    description:
        本类是用来展示通用信号的 trace 窗体
        这个类一定好好写，认真写
        这个类很重要
    args:
        parant 'QWidget' 父窗体
    return:
        None
    '''

    def __init__(
        self, 
        parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None:
        ###########################################
        super().__init__(parent=parent)

        # 设置类内数据 ====================================
        self.parentHeaderConfig = dict()
        self.childHeaderConfig = dict()
        self._itemBackUpList = list()           # 存放 backup
        self.setHeader(HorizontalHeaderView())
        self._hHeader = self.header()
        self._hHeaderItem = self.headerItem()
        self.isContinue = True
        # ================================================

        # 添加 Action ======================================
        self.actionPasueContinue = QAction()
        self.actionPasueContinue.triggered.connect(self.ActionPauseContinue)
        self.actionPasueContinue.setText('Pause')
        # =================================================

        # 构造函数 ========================================
        self.setMouseTracking(False)
        # ================================================
    
    def AddRows(self, items: typing.List['TreeWidgetItemABC']) -> None:
        '''
        添加一行数据:
            按照规定的格式添加，
        '''
        if (self.isContinue):

            # pass
            # 如果当前是 continue 状态 ===========
            # while (self.invisibleRootItem().childCount() > 2000):
                # self.invisibleRootItem().
                # self.invisibleRootItem().removeChild(self.invisibleRootItem().child(0))
            # if (self.invisibleRootItem().childCount() > 1000):
            #     self.invisibleRootItem().removeChild(self.invisibleRootItem().child(0))
            # item.setFlags(Qt.NoItemFlags)
            self.invisibleRootItem().addChildren(items)
            # hide_count_ = self.invisibleRootItem().childCount() - 2000
            # if (hide_count_ > 0):
            #     for i_ in reversed(range(hide_count_)):
            #         item_ = self.invisibleRootItem().child(i_)
            #         item_.setHidden(True)
            remove_count_ = self.invisibleRootItem().childCount() - 4000
            if (remove_count_ > 0):
                for i_ in range(remove_count_):
                    self.invisibleRootItem().removeChild(self.invisibleRootItem().child(i_))
        else:
            # 如果当前是 Pause 状态 ==============
            self._AddBackUpTreeItem(items)

    def ActionPauseContinue(self, checked: 'bool') -> None:
        '''
        function:
            暂停，启动动作
        '''
        self.isContinue = not self.isContinue
        if (self.isContinue):
            self.actionPasueContinue.setText('Pause')
            # while(len(self._itemBackUpList) > 0):
            self.AddRows(self._itemBackUpList)
            self._itemBackUpList.clear()
        else:
            self.actionPasueContinue.setText('Continue')
        
    def UpdateHeaderConfig(
        self, 
        parent_header_config: typing.Dict['str', 'dict'], 
        child_header_config: typing.Dict['str', 'dict']) -> None:
        '''
        function:
            更新本对象的 header_config
        '''
        self.parentHeaderConfig = parent_header_config
        self.childHeaderConfig = child_header_config
        for header_name_, config_ in parent_header_config.items():
            index_ = config_.get('index', None)
            if (not isinstance(index_, int)):
                continue
            self._hHeaderItem.setText(index_, header_name_)
        for index_ in range(self.invisibleRootItem().childCount()):
            item_ = self.invisibleRootItem().child(index_)
            if (not isinstance(item_, TreeWidgetItemABC)):
                continue
            item_.Refresh(self.parentHeaderConfig, self.childHeaderConfig)

    def _AddBackUpTreeItem(self, items: typing.List['TreeWidgetItemABC']) -> None:
        '''
        function:
            往 backup item list 中添加 item
        '''
        while (len(self._itemBackUpList) > 500):
            self._itemBackUpList.pop(0)
        self._itemBackUpList.extend(items)
            # self.invisibleRootItem().removeChild(self.invisibleRootItem().child(0))
        # if (not len(self._itemBackUpList) > 500):
            # self._itemBackUpList.
            # self._itemBackUpList.extend(items)

